﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.SessionState;
using System.IO;
using System.Drawing;
using FmcWebsite.Core;

namespace FmcWebsite.Web
{
    public class WebAttachmentImage
    {
        private AttachmentIMAGE image;

        public WebAttachmentImage(AttachmentIMAGE img, HttpSessionState session)
        {
            image = img;
        }

        public string ContentType
        {
            get { return image.ContentType; }
        }

        public long Save(Stream stream)
        {
            return image.Save(stream);
        }

        public long Save(Stream stream, int min_side)
        {
            Image source = image.Image;

            Bitmap target;

            if (source.Width >= source.Height)
            {
                target = new Bitmap((min_side * source.Width) / source.Height, min_side);
            }
            else
            {
                target = new Bitmap(min_side, (min_side * source.Height) / source.Width);
            }

            var gr = Graphics.FromImage(target);
            gr.DrawImage(
                source,
                new Rectangle(0, 0, target.Width, target.Height),
                new Rectangle(0, 0, source.Width, source.Height),
                GraphicsUnit.Pixel);

            target.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

            return 0;
        }

        public string GetUrl()
        {
            return "/AttachmentImage.ashx?id=" + image.Id.ToString();
        }

        static public WebAttachmentImage ById(int att_id, HttpSessionState session)
        {
            Attachment att = Attachment.ById(att_id);
            if (att is AttachmentIMAGE)
            {
                return new WebAttachmentImage((AttachmentIMAGE)att, session);
            }
            return null;
        }

        static public IEnumerable<WebAttachmentImage> GetSlides(HttpSessionState session)
        {
            foreach (AttachmentIMAGE i in AttachmentIMAGE.GetSlides())
                yield return new WebAttachmentImage(i, session);
        }
    }
}
